package cc.linker.steplink.crm.merchant.service;


import cc.linker.steplink.crm.commons.Constants;
import cc.linker.steplink.crm.commons.RandomCodeGenerator;
import cc.linker.steplink.crm.merchant.dao.PersonnelDao;
import cc.linker.steplink.crm.merchant.task.EmailSendCallable;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.*;

@Slf4j
@Service
public class PersonnelService {

    @Autowired
    private PersonnelDao personnelDao;

    //统计失败次数
    private int x = 0;

    public List<Map<String, Object>> getList(Map<String, String> map) {
        return personnelDao.getList(map);
    }

    public void del(long authorId) {
        personnelDao.del(authorId);
    }

    public HashSet<String> getDomainList(String orgId) {
        HashSet<String> res = new HashSet<>();
        List<String> domainList = personnelDao.getDomainList(orgId);
        if (null != domainList && domainList.size() > 0) {
            for (String da : domainList) {
                if (StringUtils.isNotEmpty(da)) {
                    String[] split = da.split(",");
                    res.addAll(Arrays.asList(split));
                }
            }
        }
        return res;
    }

    public void addCustomer(String orgId) {
        int count = personnelDao.getCustomerCount(orgId);
        if (count > 0) {
            return;
        }
        Map<String, String> map = new HashMap<>();
        map.put("orgId", orgId);
        List<Map<String, Object>> list = personnelDao.getList(map);
        for (Map<String, Object> da : list) {
            String customerId = RandomCodeGenerator.getCustomerId(Constants.CUSTOMER_CODE_SOURCE_RC);
            da.put("customerId", customerId);
            da.put("orgId", orgId);
            da.put("customerSourceChannel", 99);
            personnelDao.addCustomer(da);
            personnelDao.addAuthorCustomer(da);
        }
    }

    public Map<String, Object> getDetail(String authorId) {
        Map<String, Object> detail = personnelDao.getDetail(authorId);
        if (!StringUtils.isEmpty((String) detail.get("nodes"))) {
            detail.put("nodes", JSON.parseArray(detail.get("nodes").toString()));
        } else {
            detail.put("nodes", new ArrayList<>());
        }
        if (!StringUtils.isEmpty((String) detail.get("links"))) {
            detail.put("links", JSON.parseArray(detail.get("links").toString()));
        } else {
            detail.put("links", new ArrayList<>());
        }
        String email = detail.get("email").toString();
        detail.put("readTimes", new ArrayList<>());

        // 根据邮箱查询发送情况
        if (!StringUtils.isEmpty(email)) {
            List<Map<String, Object>> readInfoIdByPid = personnelDao.getReadInfoIdByEmail(email);
            detail.put("readTimes", readInfoIdByPid);
        }

        return detail;
    }

    public void saveRemark(String authorId, String remark) {
        personnelDao.saveRemark(authorId, remark);
    }


    /**
     * 给人才发送邮件
     *
     * @param map 邮件参数 content：内容
     **/
    @Async("EmailDemoExecutor")
    public void sendEmailToPesonnal(Map<String, Object> map,List<String> emails) throws InterruptedException, ExecutionException {

        String content = (String) map.get("contentTest");
        String taskName = (String) map.get("taskName");
        String taskId = (String) map.get("taskId");
        String orgId = (String) map.get("orgId");
        List<String> allEmails ;
        if (org.apache.commons.lang.StringUtils.isNotEmpty(content)) {
            if (CollectionUtils.sizeIsEmpty(emails)) {
                //邮件列表【一期】
                allEmails = personnelDao.selectPersonelEmailListByType(map);
            }else{
                //邮件列表【二期】
                allEmails = JSON.parseArray(JSON.toJSONString(emails), String.class);
            }
            LOGGER.info("测试数据为一共" + allEmails.size() + "条");

            // 进行异步邮件发送 ！！！！
            ExecutorService threadPool = Executors.newCachedThreadPool();
            CompletionService<Integer> cs = new ExecutorCompletionService<Integer>(threadPool);

            for (String email : allEmails) {
                cs.submit(new EmailSendCallable(email, content, taskName, orgId, taskId));
            }

            // 更新触达成功数量
            Integer successCount = Integer.valueOf(0);
            for(int i = 0; i < allEmails.size(); i++) {

                //take()方法 从队列中获取到一个执行完成的任务并且移除该任务，如果队列中没有的话就会进行阻塞
                successCount = successCount + cs.take().get();
            }
            LOGGER.info("-----------》推送成功之后："+successCount);
            personnelDao.updateSuccessCountByTaskId(successCount,taskId);

            //更新原来业务表 t_crm_tbl_precise_list触达人数
            personnelDao.updatePreciseList(successCount,taskId);
        }

    }

    // 按照用户类型进行分组统计
    public List<Map<String, String>> selectPersonelCountByType(Map<String, String> map) {
        return personnelDao.selectPersonelCountByType(map);
    }

    // 根据用户类型查询邮件列表
    public List<String> selectPersonelEmailListByType(Map<String, Object> map) {
        return personnelDao.selectPersonelEmailListByType(map);
    }


}
